package services

import (
	"database/sql"
	"go-db/sqldb"
	"go-db/sqldb/dao"
	"go-db/sqldb/entity"
	"time"

	"github.com/eyediy/dbcontrol"
)

type user struct {
	db  *sqldb.Database
	dao struct {
		user        dao.User
		userProfile dao.UserProfile
	}
}

var (
	User = &user{}
)

func (t *user) Bind(db *sqldb.Database) {
	t.db = db
	t.dao.user.Bind(db)
	t.dao.userProfile.Bind(db)
}

//Create 创建用户
// args 参数列表
//	Name
//	Pass
// returns
//	用户ID, error
func (t *user) Create(args map[string]interface{}) (_userID int64, _err error) {
	var err error
	var fields []string
	var user *entity.User
	var userProfile *entity.UserProfile
	var userIDs []int64
	var result sql.Result
	var nRowsAffected int64
	var tx *dbcontrol.Tx

	// 开始事务
	tx, err = t.db.DB().Begin()
	if err != nil {
		return 0, err
	}
	defer transactionHandler(tx, &_err)

	args["TCreate"] = time.Now().Unix()
	for k, _ := range args {
		fields = append(fields, k)
	}

	user = &entity.User{}
	user.Name = args["Name"].(string)
	user.Pass = args["Pass"].(string)
	user.TCreate = args["TCreate"].(int64)

	fields = append(fields, "hidden_original_password")
	hiddenValues := []map[string]interface{}{
		{"hidden_original_password": user.Pass},
	}
	user.Pass = encPassword(user.Pass)

	// 1.添加user记录
	userIDs, err = t.dao.user.AddWithReturningID(tx, "ID", fields, hiddenValues, user)
	if err != nil {
		panic(err)
	}
	if len(userIDs) != 1 {
		panic("[services/user] len(userIDs)!=1")
	}

	userProfile = &entity.UserProfile{}
	userProfile.UID = userIDs[0]

	// 2.使用用户ID创建profile记录
	result, err = t.dao.userProfile.Add(tx, []string{"UID"}, nil, userProfile)
	if err != nil {
		panic(err)
	}
	nRowsAffected, err = result.RowsAffected()
	if err != nil {
		panic(err)
	}
	if nRowsAffected != 1 {
		panic("[services/user] result.RowsAffected() != 1")
	}

	// 3.使用用户ID创建asset记录

	return userIDs[0], nil
}
